﻿﻿using System;
using System.Collections.Concurrent;
using System.Text;


    public class ReceiveDataUnpack
    {
      private byte[] dataBuffer = new byte[1024];
      private byte[] tempBuffer;
      private int tempBufferIndex = 0;

      private const int HEAD_SIZE = 4;
      
        private String receiveString;
        private int receiveContentNum = 0;
        private int ContentNum = 0;

        private bool isFirstCopy = true;
        private bool isReadHead = true;
        private bool isReceiveAll = true;
        public byte[] DataBuffer
        {
            get { return dataBuffer; }
        }

        public String ReceiveStr
        {
            get { return receiveString; }
        }

        private bool isread = false;
        private bool isDone = false;

        public bool isRead
        {
            get { return isread; }
        }

        public void ReadMessage(int IndataNum)
        {
            receiveContentNum += IndataNum;
             if (isReadHead)
             {
                 ContentNum = BitConverter.ToInt32(dataBuffer, 0);
                 tempBuffer = new byte[ContentNum];
                 if (receiveContentNum>ContentNum)
                 {
                     isReceiveAll = true;
                 }
                 else
                 {
                     isReceiveAll = false;
                     tempBufferIndex = receiveContentNum - HEAD_SIZE;
                 }
                 
                 isReadHead = false;
                 isFirstCopy = true;
                 isread = false;
             }
             
             if (receiveContentNum - HEAD_SIZE <= ContentNum &&!isReceiveAll)
             {
                 if (isFirstCopy)
                 {
                     
                     Array.Copy(dataBuffer, HEAD_SIZE, tempBuffer, 0, receiveContentNum - HEAD_SIZE);
                     isFirstCopy = false;
                 }
                 else 
                 {
                     Array.Copy(dataBuffer, 0, tempBuffer, tempBufferIndex, IndataNum);
                     tempBufferIndex += dataBuffer.Length;
                     if (receiveContentNum - HEAD_SIZE == ContentNum)
                     {
                         isDone = true;
                     }
                 }
             }
             
             if (isReceiveAll)
             {
                 Array.Copy(dataBuffer,HEAD_SIZE,tempBuffer,0,tempBuffer.Length);
                 isDone = true;
             }

             if(isDone)
             {
                 isread = true;
                 receiveString = Encoding.UTF8.GetString(tempBuffer, 0, tempBuffer.Length);
                 receiveContentNum = 0;
                 isReadHead = true;
                 isDone = false;
             }
        }
    }
